import express from "express";
import { asyncHandler } from "../middleware/asyncHandler";
import { User } from "../../model/models/User";
import { MyFileDir } from "@/model/init";
import { Op } from "sequelize";
import { History } from "@/model/models/History";
import { groupBy } from "../../utils/groupBy";
const router = express.Router();

async function getUserHistory(uid: number, data?: Date, needAll: boolean = false) {
    let where: any = {};
    if (data) {
        const start = new Date(data.getFullYear(), data.getMonth(), data.getDate()); // 当天最开始的时间
        const end = new Date(data.getFullYear(), data.getMonth(), data.getDate() + 1); // 当天最晚的时间，即明天的开始时间
        where.createdAt = {
            [Op.gte]: start,
            [Op.lt]: end,
        };
    }

    let result = await User.findAll({
        where: {
            id: uid,
        },
        attributes: {
            exclude: ["createdAt", "updatedAt", "deletedAt"],
        },
        include: [
            {
                model: MyFileDir,
                attributes: ["path", "id"],
                through: {
                    attributes: ["createdAt", "id"],
                    where: {},
                    paranoid: !needAll,
                },
                as: "HistoryMyFileDir",
            },
        ],
    });
    return result[0]?.dataValues.HistoryMyFileDir || [];
}

router.get(
    "",
    asyncHandler(async (req, res) => {
        let uid = (req as any).user.userId;
        let result = await getUserHistory(uid);
        let obj = groupBy(result, (item: any) => {
            let date = item.dataValues.History.dataValues.createdAt as Date;
            return date.toLocaleDateString();
        });
        result = [];
        for (let key in obj) {
            let o = {
                date: key,
                data: obj[key],
            };
            result.push(o);
        }
        return result;
    })
);

router.post(
    "",
    asyncHandler(async (req, res) => {
        let fileId = req.body.fileId;
        let uid = (req as any).user.userId;
        let histories = (await getUserHistory(uid, new Date())) as any[];
        let history = histories.filter((item: any) => item.dataValues.id == fileId);
        if (history.length != 0) {
            // 有记录修改记录
            let historyId = history[0].dataValues.History.id;
            History.update(
                {
                    fileId,
                },
                {
                    where: {
                        id: historyId,
                    },
                }
            );
        } else {
            // 没有记录创建记录
            let user = (await User.findByPk(uid))!;
            let file = await MyFileDir.findByPk(fileId);
            // 创建一条记录
            await (user as any).addHistoryMyFileDir(file);
        }

        return "添加成功";
    })
);

router.delete(
    "/:id",
    asyncHandler(async (req, res) => {
        let id = (req.params as any).id;
        let result = await History.destroy({
            where: {
                id,
            },
        });
        if (result === 0) {
            throw new Error("删除失败");
        } else {
            return "删除成功";
        }
    })
);

export default router;
